package tongwentongshu.com.app.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.RegeocodeResult;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.bean.BookTypeBean;
import tongwentongshu.com.app.bean.OrderEvent;
import tongwentongshu.com.app.bean.RqcordBook;
import tongwentongshu.com.app.bean.ShareBean;
import tongwentongshu.com.app.contract.CallBackColonyContract;
import tongwentongshu.com.app.contract.ShareBookContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.dialog.AlertUtils;
import tongwentongshu.com.app.model.ShareBookModel;
import tongwentongshu.com.app.presenter.ShareBookPresenter;
import tongwentongshu.com.app.update.DownLoadImageService;
import tongwentongshu.com.app.update.ImageDownLoadCallBack;
import tongwentongshu.com.app.utils.GlideUtil;
import tongwentongshu.com.app.utils.ToastUtil;
import tongwentongshu.com.app.zxing.CaptureActivity;

import static tongwentongshu.com.app.App.CODE;
import static tongwentongshu.com.app.App.NAME;
import static tongwentongshu.com.app.App.POINT;

/**
 * 分享图书页面
 * Created by XiongBin on 2017/6/27.
 */

public class ShareBookActivity extends BaseActivity implements ShareBookContract.View {
    @BindView(R.id.title_back)
    ImageView back;//返回键
    @BindView(R.id.title_complete)
    TextView complete;//确认分享
    @BindView(R.id.iv_code_scanning)
    ImageView btn_code;//一维码扫码按钮
    @BindView(R.id.iv_cover)
    ImageView cover;//封面图
    @BindView(R.id.iv_back_cover)
    ImageView back_cover;//封底图
    @BindView(R.id.tv_book_type)
    TextView book_type;//书籍类别
    @BindView(R.id.tv_new_old)
    TextView old_degree;//新旧程度
    @BindView(R.id.tv_position)
    TextView now_position;//当前位置
    @BindView(R.id.et_price)
    EditText price;//价格
    @BindView(R.id.et_code)
    EditText code;//条形码
    @BindView(R.id.et_introduction)
    EditText introduction;//简介
    @BindView(R.id.et_book_name)
    EditText book_name;//书名

    private int mWidth;
    private int mHeight;
    private boolean currentImageView = false;//true封面false封底
    private boolean currentWheel = false;//true书籍类别false新旧程度

    private ShareBookPresenter shareBookPresenter;
    private ShareBookModel shareBookModel;
    /**
     * 临时存储参数
     */
    private String coverUrl;//封面图URL
    private String backCoverUrl;//底面图URL
    private int booktype_ID = -1;//书籍类别id
    private int olddegree_ID = -1;//新旧程度id

    private PoiItem poiItem;//当前poi

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_sharebook;
    }

    @Override
    protected int getTitleId() {
        return R.string.pager_share;
    }

    @Override
    protected void initView() {
        int por = getIntent().getExtras().getInt("por", -1);
        if (por != -1) {
            RqcordBook b = (RqcordBook) getIntent().getExtras().getSerializable("rqcordBook");
            setCodeData(b);
        }
        complete.setVisibility(View.VISIBLE);
        code.setFocusable(false);
        code.setFocusableInTouchMode(false);
        shareBookPresenter = new ShareBookPresenter(this);
        shareBookPresenter.getBookType();
        shareBookPresenter.setPricePoint(price);
        shareBookModel = new ShareBookModel(this);
        cover.post(new Runnable() {
            @Override
            public void run() {
                mWidth = cover.getWidth();
                mHeight = cover.getHeight();
            }
        });
    }

    @Override
    protected void initData() {
        shareBookPresenter.getAddress(this);
    }

    @Override
    protected void initListener() {
        super.initListener();
    }


    private String[] new_old_list = {"全新", "九成新", "八成新", "七成新", "六成新", "五成新"};

    @OnClick({R.id.iv_back_cover, R.id.iv_cover, R.id.tv_position, R.id.tv_book_type, R.id.tv_new_old, R.id.iv_code_scanning, R.id.title_complete, R.id.tv_share_gui})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_share_gui:
                Bundle b1 = new Bundle();
                b1.putString("url", "http://tongwentongshu.cn/index.php?g=&m=Index&a=get_share_rule&type=1");
                startActivity(WebViewActivity.class, b1);
//                shareBookPresenter.codeSearch("9787544270878");
                break;
            case R.id.iv_code_scanning:
                Bundle codeb = new Bundle();
                codeb.putBoolean("source", false);//true是从首页进入，false是从分享页进入
                startActivityForResult(CaptureActivity.class, codeb, 0);
//                startCamera(Manifest.permission.CAMERA);

//                shareBookPresenter.codeSearch("9787544270878");
                break;
            case R.id.iv_cover:
                currentImageView = true;
                AlertUtils.initPhotoAlertDialog(this, onPhotoType);
                break;
            case R.id.iv_back_cover:
                currentImageView = false;
                AlertUtils.initPhotoAlertDialog(this, onPhotoType);
                break;
            case R.id.tv_book_type:
                currentWheel = true;
                AlertUtils.initWheelDialog(this, book_type_list, booktype_ID, onWheelBack);
                break;
            case R.id.tv_new_old:
                currentWheel = false;
                AlertUtils.initWheelDialog(this, new_old_list, olddegree_ID, onWheelBack);
                break;
            case R.id.tv_position:
                Bundle b = new Bundle();
                ArrayList<PoiItem> list = (ArrayList<PoiItem>) shareBookPresenter.getPoiList();
                if (list != null)
                    b.putParcelableArrayList("poi_list", list);
                startActivityForResult(SelectLocationActivity.class, b, 0);
                break;
            case R.id.title_complete:
                if (Cache.LoginVer(mContext))
                    return;
                if (initCheck())
                    if (Cache.getUser().getData().getUser_status().equals("2")) {
                        AlertUtils.showAgainShare(mContext, "认 证后才可以分享书籍哦，是否去认证？", "稍后认证", "立即认证", 2, new CallBackColonyContract.OnDiyClick() {
                            @Override
                            public void left() {

                            }

                            @Override
                            public void right() {
                                startActivity(RealNameAuthenticationActivity.class);
                            }
                        });

                        return;
                    }
                if (initCheck())
                    AlertUtils.showAgainShare(mContext, "懂得分享的人最快乐！", "稍后分享", "立即分享", 2, new CallBackColonyContract.OnDiyClick() {
                        @Override
                        public void left() {

                        }

                        @Override
                        public void right() {

                            AlertUtils.showLoding(mContext);
                            submit();
                        }
                    });

                break;
        }
    }


    /**
     * 选择图片弹窗监听
     */
    public CallBackColonyContract.OnPhotoType onPhotoType = new CallBackColonyContract.OnPhotoType() {

        @Override
        public void photoAlbum() {
            shareBookModel.getFileByPhotoAlbum(ShareBookActivity.this);
            shareBookModel.compressSize(mWidth, mHeight);
        }

        @Override
        public void photograph() {
            shareBookModel.getFileByPhotograph(ShareBookActivity.this);
            shareBookModel.compressSize(mWidth, mHeight);
        }
    };
    /**
     * 选取新旧程度、书籍类别弹窗监听
     */
    public CallBackColonyContract.OnWheelBack onWheelBack = new CallBackColonyContract.OnWheelBack() {

        @Override
        public void wheelCallBack(int index) {
            if (currentWheel) {
                booktype_ID = index;
                book_type.setText(book_type_list[booktype_ID % book_type_list.length]);
            } else {
                olddegree_ID = index;
                old_degree.setText(new_old_list[olddegree_ID % new_old_list.length]);
            }
            AlertUtils.dismiss();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        shareBookModel.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 权限选择后
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        shareBookModel.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void shareOnSuccess(ShareBean bean) {
        Bundle b = new Bundle();
        b.putString("bookid", bean.getData().getBookid());
        b.putString("bookname", book_name.getText().toString().trim());
        b.putString("img", bean.getData().getImg());
        startActivity(ShareCompleteActivity.class, b);
        finish();
    }

    /**
     * 选择图片填充
     */
    @Override
    public void setBookImage(Bitmap bitmap, String url) {
        if (currentImageView) {
            cover.setImageBitmap(bitmap);
            coverUrl = url;
        } else {
            back_cover.setImageBitmap(bitmap);
            backCoverUrl = url;
        }
    }


    public void onEventMainThread(OrderEvent result) {
        poiItem = result.getResult();
//        ToastUtil.show(mContext, result.getResult().getTitle());
        System.out.println("我收到了eventBus的消息");
    }

    @Override
    public void setLocation(String location_string) {
        now_position.setText(location_string);
    }

    boolean codetransmit = false;

    @Override
    public void setCodeData(RqcordBook b) {
        if (null != b) {
            if (TextUtils.isEmpty(b.getData().getBook_money())) {
                codetransmit = true;
                price.setFocusable(true);
                price.setFocusableInTouchMode(true);
                price.requestFocus();
            } else {
                codetransmit = false;
                price.setFocusable(false);
                price.setFocusableInTouchMode(false);
                price.setText(b.getData().getBook_money());
                introduction.setText(b.getData().getBook_introduce());
                book_name.setText(b.getData().getBook_name());
                code.setText(b.getData().getRqcord());
                onDownLoad(b.getData().getImagehead());
                GlideUtil.setImage1(mContext, b.getData().getImagehead(), R.drawable.default_graph, R.drawable.default_graph, cover);
            }
        }
    }

    @Override
    public void setPoiItem(PoiItem p) {
        poiItem = p;
    }

    private String[] book_type_list;

    //            = {"教育", "历史", "散文", "计算机", "高考书籍", "小说", "诗词"};
    @Override
    public void setBookType(BookTypeBean msg) {
        this.msg = msg;
        book_type_list = new String[msg.getData().size()];
        for (int i = 0; i < msg.getData().size(); i++) {
            book_type_list[i] = msg.getData().get(i).getName();
        }

    }

    private Bitmap bitmap;

    @Override
    public Bitmap getImg() {
        return bitmap;
    }

    /**
     * 启动图片下载线程
     */
    private void onDownLoad(String url) {
        DownLoadImageService service = new DownLoadImageService(getApplicationContext(),
                url,
                new ImageDownLoadCallBack() {

                    @Override
                    public void onDownLoadSuccess(File file) {
                    }

                    @Override
                    public void onDownLoadSuccess(Bitmap bitmap, String path) {
                        // 在这里执行图片保存方法
                        coverUrl = path;
                        ShareBookActivity.this.bitmap = bitmap;
                        Log.e(TAG, "path=" + path);
                    }

                    @Override
                    public void onDownLoadFailed() {
                        // 图片保存失败
                    }
                });
        //启动图片下载线程
        new Thread(service).start();
    }

    BookTypeBean msg;
    /**
     * 提交参数
     */
    private Map<String, String> map;
    private AMapLocation location;
    private RegeocodeResult result;

    boolean initCheck() {
        String bookNameStr = book_name.getText().toString().trim();
        String introductionStr = introduction.getText().toString().trim();
        String priceStr = price.getText().toString().trim();
        if (TextUtils.isEmpty(bookNameStr)) {
            ToastUtil.show(mContext, "书名不能为空");
            return false;
        }
        if (TextUtils.isEmpty(introductionStr)) {
            ToastUtil.show(mContext, "描述不能为空");
            return false;
        }
        if (TextUtils.isEmpty(priceStr)) {
            ToastUtil.show(mContext, "价格不能为空");
            return false;
        }
        if (TextUtils.isEmpty(coverUrl)) {
            ToastUtil.show(mContext, "请选择封面图");
            return false;
        }
        if (booktype_ID == -1) {
            ToastUtil.show(mContext, "请选择书籍分类");
            return false;
        }
        if (olddegree_ID == -1) {
            ToastUtil.show(mContext, "请选择新旧程度");
            return false;
        }
        return true;
    }

    private void submit() {
        map = new ArrayMap<>();

        String codeStr = code.getText().toString().trim();
        String bookNameStr = book_name.getText().toString().trim();
        String introductionStr = introduction.getText().toString().trim();
        String priceStr = price.getText().toString().trim();
        map.put("token", Cache.getToken());//token
        if (!codetransmit)
            map.put("code", codeStr);//条形码值
        map.put("book_name", bookNameStr);//书名
        map.put("book_introduce", introductionStr);//书描述
        map.put("book_type_id", msg.getData().get(booktype_ID).getId());//书籍分类ID
        map.put("book_new_old", new_old_list[olddegree_ID]);//新旧程度
        map.put("book_money", priceStr);//价格
        location = shareBookPresenter.getAMapLocation();
        map.put("province", location.getProvince());//省
        map.put("city_name", location.getCity());//市
        map.put("district_name", location.getDistrict());//区
        result = shareBookPresenter.getRegeocodeResult();
        map.put("street_name", shareBookPresenter.getStreet().get(NAME));//商圈名称
        map.put("stree_map", shareBookPresenter.getStreet().get(POINT));//商圈坐标
        if (!TextUtils.isEmpty(shareBookPresenter.getStreet().get(CODE))) {
            map.put("stree_code", shareBookPresenter.getStreet().get(CODE));//商圈编码
        }
        map.put("tradingarea_name", shareBookPresenter.getTradingarea().get(NAME));//aois名称
        map.put("tradingarea_map", shareBookPresenter.getTradingarea().get(POINT));//aois坐标
        map.put("tradingarea_code", shareBookPresenter.getTradingarea().get(CODE));//sois编码
        map.put("book_postition", poiItem.getTitle());//当前位置
        map.put("book_postition_map", poiItem.getLatLonPoint().getLongitude() + "," + poiItem.getLatLonPoint().getLatitude());//当前位置坐标
        shareBookPresenter.Submit(map, coverUrl, backCoverUrl);

    }

}
